import { useState, useEffect } from "react";
import "./App.css";

function ChildComponent(props) {
    console.log("call ChildComponent function");

    const [updateCount, setUpdateCount] = useState(0);

    useEffect(() => {
        console.log("ChildComponent: mounted effect");
        return () => {
            console.log("ChildComponent: mounted effect - cleanup");
        };
    }, []);

    useEffect(() => {
        console.log("ChildComponent: updating effect");

        return () => {
            console.log("ChildComponent: updating effect - cleanup ");
        };
    });

    function handleClick() {
        console.log("clicked update button");
        setUpdateCount(updateCount + 1);
    }

    return (
        <div className="child">
            <h2>ChildComponent</h2>
            <p>
                props.count={props.count}, updateCount={updateCount}
            </p>
            <button onClick={handleClick}>更新ChildComponent</button>
        </div>
    );
}

function App() {
    console.log("call App function");

    const [toggle, setToggle] = useState(false);
    const [count, setCount] = useState(0);

    function handleClick(e) {
        console.log("clicked mount/unmount button");
        setToggle(toggle ? false : true);
        setCount(count + 1);
    }

    return (
        <div className="container">
            <h1>装载(Mount)、卸载(Unmount)、更新(Update)演示</h1>
            <button type="button" onClick={handleClick}>
                {toggle ? "卸载ChildComponent" : "装载ChildComponent"}
            </button>
            {toggle && <ChildComponent count={count} />}
        </div>
    );
}

export default App;
